<template>
  <div style="background-color: white; margin-top: -5px">
    <van-sticky :offset-top="47">
      <el-alert
        :title="infoAlert.title"
        :type="infoAlert.type"
        center
        show-icon
        :closable="false"
        style="margin-bottom: 15px"
      ></el-alert>
    </van-sticky>
    <van-form @submit="submitForm">
      <van-field
        v-model="form.projectOn"
        label="项目编号"
        placeholder="立项表提交后自动生成"
        readonly
      />
      <van-field
        v-model="form.projectName"
        label="项目名称"
        placeholder="请输入项目名称"
        :rules="[{ required: true, message: '请输入项目名称' }]"
      />
      <DeptTreePicker
        ref="treePicker"
        v-model="form.deptId"
        label="所属部门"
        :rules="[{ required: true, message: '请选择归属部门' }]"
      />
      <searchable-picker
        v-model="form.customerId"
        :columns="customerList"
        valueKey="customerId"
        labelKey="customerName"
        label="客户名称"
        placeholder="点击选择客户名称"
        :rules="[{ required: true, message: '客户不能为空' }]"
      />
      <searchable-picker
        v-model="form.applyUser"
        :columns="userList"
        valueKey="userId"
        labelKey="userName"
        label="申请人"
        placeholder="请选择申请人"
        :rules="[{ required: true, message: '申请人不能为空' }]"
      />
      <searchable-picker
        v-model="form.principalId"
        multiSelect
        :columns="userList"
        valueKey="userId"
        labelKey="userName"
        label="负责人"
        placeholder="请选择负责人"
        :rules="[{ required: true, message: '负责人不能为空' }]"
      />
      <van-field
        v-model="form.startTime"
        label="开始日期"
        placeholder="请选择开始日期"
        @click="startTimeFlag = true"
        :rules="[{ required: true, message: '开始日期不能为空' }]"
      />
      <van-calendar
        v-model="startTimeFlag"
        @confirm="onConfirm($event, 'startTimeFlag', 'startTime')"
        :min-date="minDate"
        :max-date="maxDate"
      />

      <van-field
        v-model="form.endTime"
        label="结束日期"
        placeholder="请选择结束日期"
        @click="endTimeFlag = true"
        :rules="[{ required: true, message: '结束日期不能为空' }]"
      />
      <van-calendar
        v-model="endTimeFlag"
        @confirm="onConfirm($event, 'endTimeFlag', 'endTime')"
        :min-date="minDate"
        :max-date="maxDate"
      />
      <van-field
        v-model="form.payment"
        label="回款情况"
        placeholder="请输入回款情况说明"
        :rules="[{ required: true, message: '回款情况不能为空' }]"
      />
      <van-field
        v-model="form.projectSum"
        label="项目金额"
        type="number"
        placeholder="请输入项目金额"
        :rules="[{ required: true, message: '项目金额不能为空' }]"
      />

      <van-field
        v-model="form.profit"
        label="最终利润"
        type="number"
        placeholder="请输入最终利润"
        :rules="[{ required: true, message: '最终利润不能为空' }]"
      />

      <van-field
        v-model="form.profitMargin"
        label="利润率"
        type="number"
        placeholder="填写预计利润后自动计算"
        readonly
      />

      <div class="details">
        <div class="details-header">项目成本费用支出</div>
        <van-collapse
          v-model="activeNames"
          class="product"
          v-for="(details, index) in form.detailsList"
          :key="index"
        >
          <van-collapse-item
            :title="'详情' + (index + 1)"
            :name="index + 1"
            icon="ellipsis"
            class="details-body"
          >
            <div class="details-button">
              <el-button type="text" @click="addExpenses(details, index)"
                >新增</el-button
              >
              <el-button
                type="text"
                style="color: red"
                @click="delExpenses(index)"
                v-if="details.flag !== '1'"
                >删除</el-button
              >
            </div>
            <van-field name="checkbox" label="无明细">
              <template #input>
                <van-checkbox
                  v-model="details.isRequired"
                  shape="square"
                  :disabled="
                    details.detailsAmount !== null &&
                    details.detailsAmount !== ''
                  "
                />
              </template>
            </van-field>
            <searchable-picker
              v-model="details.detailsType"
              :columns="dict.type.crm_fee_type"
              :readonly="details.flag === '1'"
              :disabled="details.isRequired"
              valueKey="value"
              labelKey="label"
              label="费用类型"
              placeholder="点击选择费用类型"
              :rules="[{ required: true, message: '费用类型不能为空' }]"
            />
            <searchable-picker
              v-model="details.applyIds"
              :columns="applyList"
              :disabled="details.isRequired === '1' || details.flag === '1'"
              v-if="details.detailsType === '1' || details.detailsType === '4'"
              valueKey="applyId"
              labelKey="applyName"
              multiSelect
              label="费用来源"
              placeholder="点击选择费用来源"
              @change="setterApplyAmount($event, details)"
            />
            <van-field
              v-model="details.detailsName"
              label="费用名称"
              placeholder="请输入费用名称"
              :rules="[
                { required: !details.isRequired, message: '费用名称不能为空' },
              ]"
              :readonly="details.flag === '1'"
              :disabled="details.isRequired"
            />
            <van-field
              v-model="details.detailsDesc"
              label="费用描述"
              placeholder="请输入费用详情描述"
              :disabled="details.isRequired"
            />
            <van-field
              v-model="details.detailsAmount"
              label="预算合计"
              placeholder="请输入预算合计"
              :rules="[
                { required: !details.isRequired, message: '预算合计不能为空' },
              ]"
              :disabled="details.isRequired"
            />
            <van-field
              v-model="details.remark"
              label="备注"
              placeholder="请输入备注"
              :disabled="details.isRequired"
            />
          </van-collapse-item>
        </van-collapse>
        <div class="details-footer">
          <el-button
            type="text"
            icon="el-icon-circle-plus-outline"
            @click="addExpenses(null)"
            >新增一项</el-button
          >
        </div>
        <div style="height: 10px; background-color: #eceff2"></div>
      </div>
      <van-field
        v-model="form.aggregationCharge"
        label="费用总计"
        placeholder="请输入备注"
        type="number"
        readonly
      />
      <van-field
        v-model="form.opinion"
        label="管理层意见"
        placeholder="请输入管理层意见"
      />
      <van-field name="uploader" label="文件上传" style="margin-bottom: 50px">
        <template #input>
          <file-upload v-model="form.url" />
        </template>
      </van-field>
      <div class="mobile-footer">
        <van-button
          native-type="submit"
          style="width: 49%; border-radius: 10px"
          @click="auditStatus = '0'"
          >暂存</van-button
        >
        <van-button
          type="info"
          native-type="submit"
          style="width: 49%; border-radius: 10px"
          @click="auditStatus = '1'"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import {
  selectCrmFeeApplyByOrderIdAndCreateBy
} from "@/api/crm/apply";

import {
  addClear,
  updateClear,
  orderClearInit,
  getInfoByOrderId
} from "@/api/crm/clear";

import { getUserListByStatus } from "@/api/system/user";

import { getCrmCustomerAllNoPage } from "@/api/crm/customer";

import { getOrder } from "@/api/crm/order";
export default {
  name: "OrderRegister",
  dicts: ["crm_order_nature", "crm_order_contracts", "crm_fee_type"],
  data() {
    return {
      minDate: new Date(2010, 0, 1),
      maxDate: new Date(2030, 0, 31),
      auditStatus: "",
      infoAlert: {
        type: "info",
        title: "待填写",
      },
      activeNames: [],
      applyList: [],
      form: {
        deptId: '',
        projectOn: "",
        projectName: '',
        customerId: '',
        startTime: '',
        endTime: '',
        applyUser: '',
        principalId: '',
        payment: '',
        projectSum: '',
        profit: '',
        profitMargin: '',
        detailsList: [],
      },
      userList: [],
      customerList: [],
      orderId: "",
      orderInfo: {},
      startTimeFlag: false,
      endTimeFlag: false,

      // 商机项目立项表格数据
      orderRegisterList: [],
    };
  },
  watch: {
    "form.projectSum"() {
      // 计算公司明细
      let obj = this.form?.detailsList?.find(
        (item) => "公司明细" === item.detailsName
      );
      obj.detailsAmount = (this.form.projectSum * 0.03).toFixed(2);
    },
    "form.detailsList": {
      handler(val) {
        
        if(!val) return
        // 计算支出总金额
        const totalAmount = this.form.detailsList.reduce((sum, item) => {
          const amount = parseFloat(item.detailsAmount) || 0;
          return sum + amount;
        }, 0);

        // 计算利润
        const profit = (this.form.projectSum - totalAmount).toFixed(2);
        this.$set(this.form, "profit", profit);

        // 计算利润率
        const profitMargin =
          this.form.projectSum > 0
            ? ((profit / this.form.projectSum) * 100).toFixed(2)
            : "0";
        this.$set(this.form, "profitMargin", profitMargin);

        this.form.aggregationCharge = totalAmount;
      },
      deep: true,
      immediate: true,
    },
  },
  async created() {
    this.orderId = this.$route.params.orderId;
    await this.getUserListByStatus();
    await this.getCrmCustomerAllNoPage();
    await this.getOrder();
    await this.selectCrmFeeApplyByOrderIdAndCreateBy()
    await this.getOrderCleartInfo();

  },
  mounted() {},
  methods: {
    selectCrmFeeApplyByOrderIdAndCreateBy(){
      selectCrmFeeApplyByOrderIdAndCreateBy(this.orderInfo.orderId).then(res => {
        this.applyList = res.data
      })
    },
    setterApplyAmount(rows, details){
      if(!rows ) return 
      details.detailsAmount = 0
      rows.forEach(row => {
        const apply = this.applyList.find(item => item.applyId === row)
        details.detailsAmount += apply.amount
      })
    
    },
    onConfirm(date, flag, fildes) {
      this[flag] = false;
      this.form[fildes] = `${date.getFullYear()}-${
        date.getMonth() + 1
      }-${date.getDate()}`;
    },
    async getOrder() {
      await getOrder(this.orderId).then((res) => {
        this.orderInfo = res.data;
      });
    },
    async getUserListByStatus() {
      await getUserListByStatus({ status: "0" }).then((res) => {
        this.userList = res.data;
      });
    },
    async getCrmCustomerAllNoPage() {
      await getCrmCustomerAllNoPage({}).then((res) => {
        this.customerList = res.data;
      });
    },
    async getOrderCleartInfo() {
      getInfoByOrderId(this.orderInfo.orderId).then(res => {
        this.form = res.data
        if (this.form) {
          // 根据审核状态设置提示
          switch (this.form.auditStatus) {
            case "0":
              this.infoAlert = { type: "info", title: "待提交" };
              break;
            case "1":
              this.infoAlert = { type: "warning", title: "待审核" };
              break;
            case "2":
              this.infoAlert = { type: "success", title: "审核通过" };
              break;
            case "3":
              this.infoAlert = { type: "error", title: "审核不通过" };
              break;
            case "4":
              this.infoAlert = { type: "warning", title: "审核中" };
              break;
          }

          this.form.principalId = this.form.principalId
            ? this.form.principalId.split(",")
            : null;
          console.log(this.form)
          this.coverCheck(false);
          this.buildActiveNames(this.form.detailsList)
        } else {
          orderClearInit(this.orderInfo.orderId).then((res) => {
            this.form = res.data;
            this.form.principalId = this.form.principalId
              ? this.form.principalId.split(",")
              : null;
            this.form.projectName = this.orderInfo.orderName;
            this.buildActiveNames(this.form.detailsList)
            this.coverCheck(false);
          });
        }
        
      })
    },
    buildActiveNames(arr) {
      this.activeNames = [];
      for (let i = 1; i <= arr.length; i++) {
        this.activeNames.push(i);
      }
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: '',
        projectOn: "",
        projectName: '',
        customerId: '',
        startTime: '',
        endTime: '',
        applyUser: '',
        principalId: '',
        payment: '',
        projectSum: '',
        profit: '',
        profitMargin: '',
        detailsList: [],
      }
      this.buildActiveNames(this.form.detailsList);
    },
    cancel() {
      this.reset();
      this.$emit("cancel");
    },
    // 添加明细
    addExpenses(details, index) {
      if (details) {
        this.form.detailsList.splice(index + 1, 0, {
          detailsName: details.detailsName,
          detailsType: details.detailsType,
          detailsDesc: null,
          detailsAmount: null,
          remark: null,
          isRequired: "0",
          flag: "0",
          itemWidth: details.detailsType === "1" || details.detailsType === "4" ? 8 : 12
        });
      } else {
        this.form.detailsList.push({
          detailsName: null,
          detailsType: '7',
          detailsDesc: null,
          detailsAmount: null,
          remark: null,
          isRequired: "0",
          flag: "0",
          itemWidth: 12
        });
      }
      this.buildActiveNames(this.form.detailsList);
    },
    delExpenses(index) {
      this.form.detailsList.splice(index, 1);
    },
    coverCheck(flag = true) {
      if (flag) {
        this.form.detailsList.forEach((item) => {
          item.isRequired = item.isRequired ? "1" : "0";
        });
      } else {
        this.form.detailsList.forEach((item) => {
          item.isRequired = item.isRequired === "1";
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.form.orderId = this.orderInfo.orderId;
      this.form.principalId = this.form.principalId ? this.form.principalId.join(",") : null;
      this.form.auditStatus = this.auditStatus;
      this.coverCheck();
      if (this.form.id != null) {
        updateClear(this.form).then((response) => {
          this.$toast.success("修改成功");
          this.getOrderCleartInfo();
        });
      } else {
        addClear(this.form).then((response) => {
          this.$toast.success("新增成功");
          this.getOrderCleartInfo();
        });
      }
    },
  },
};
</script>

<style scoped  lang="scss">
.submitButton {
  width: 95%;
  height: 50px;
  position: fixed;
  top: 90%;
  left: 10px;
}

::v-deep .van-collapse-item__content {
  padding: 0;
}

::v-deep .product .van-collapse-item__title {
  background-color: #eceff2;
  padding: 5px 16px;
}

.details {
  border-bottom: 1px solid #eceff2;

  .details-header {
    padding: 10px 16px 3px;
    color: #323233;
    font-size: 14px;
    line-height: 24px;
    background-color: #fff;
  }

  .details-footer {
    text-align: center;
    .el-button--text {
      font-size: 18px;
    }
  }

  .details-body {
    position: relative;
  }

  .details-button {
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 35px;
  }
}
</style>